package com.ztewatch.wearcontacts;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ztewatch.wearcontacts.loader.GroupMetaDataLoader;
import com.ztewatch.wearcontacts.service.WearContactSaveService;
import com.ztewatch.wearcontacts.utils.ConfigLoaderSelectionUtils;
import com.ztewatch.wearcontacts.utils.ContactPhotoUtils;
import com.ztewatch.wearcontacts.utils.ContactQuery;

public class WearContactEditGroupActivity extends WearContactBaseActivity
		implements OnClickListener {
	private static final int REQUEST_PHOTO_RESULT = 2;
	public static final int REQUEST_RESULT = 1;
	public static final String SAVE_GROUP_FLAG = "save_group_flag";
	public static final String EXTRA_PHONE_IDSO = "com.android.contacts.extra.PHONE_IDSO";
	public static final String EXTRA_PHONE_IDSI = "com.android.contacts.extra.PHONE_IDSI";
	private EditText mGroupNameView;
	private ImageView mGroupPhotoView;
	private LinearLayout mGroupAddressLayoutView;
	private TextView mGroupAddressNumView;
	private Button saveMenuItem;
	private MyTextWatcher mMyTextWatcher;
	private Uri groupUri;
	private long group_id;
	private String title;
	private Button mDelete_group_view;
	private ArrayList<Long> mListMembers = new ArrayList<Long>();
	private ArrayList<Long> mListMembersToAdd = new ArrayList<Long>();
	private ArrayList<Long> mListMembersToRemove = new ArrayList<Long>();
	private int image_resid = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_edit_group);
		initView();
		initActionMenu();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String action = intent.getAction();
		if (WearContactBaseActivity.ACTION_SAVE_GROUP_COMPLETED.equals(action)) {
			Intent intent1 = getIntent();
			Bundle bundle = new Bundle();
			bundle.putBoolean(SAVE_GROUP_FLAG, true);
			intent1.putExtras(bundle);
			setResult(RESULT_OK, intent1);
			finish();
		} else if (WearContactBaseActivity.ACTION_UPDATE_GROUP_COMPLETED
				.equals(action)) {
			finish();
		}
	}

//	@Override
//	public void onWindowDismissed() {
//		if (saveMenuItem.isEnabled()) {
//			showOnWindosDismissedDialog();
//			return;
//		} else {
//			super.onWindowDismissed();
//		}
//	}

	private void initView() {
		mGroupNameView = (EditText) findViewById(R.id.edit_group_name);
		mGroupPhotoView = (ImageView) findViewById(R.id.edit_group_photo_img);
		mGroupAddressLayoutView = (LinearLayout) findViewById(R.id.edit_address_l);
		mGroupAddressNumView = (TextView) findViewById(R.id.group_contact_num);
		mDelete_group_view = (Button) findViewById(R.id.delete_group_btn);
		mGroupPhotoView.setOnClickListener(this);
		groupUri = getIntent().getData();
		if (groupUri != null) {
			group_id = ContentUris.parseId(groupUri);
			mDelete_group_view.setVisibility(View.VISIBLE);
		} else {
			mDelete_group_view.setVisibility(View.GONE);
		}
		Bundle bundle = getIntent().getExtras();
		if (groupUri != null && group_id != 0) {
			title = bundle.getString(WearContactGroupListActivity.GROUP_TITLE);
			mGroupNameView.setText(title, null);
		}
		String addressNumStr = getResources()
				.getString(
						R.string.group_item_count,
						bundle.getInt(
								WearContactGroupListActivity.GROUP_DETAIL_NUM,
								0));
		mGroupAddressNumView.setText(addressNumStr);
		mMyTextWatcher = new MyTextWatcher();
		mGroupNameView.addTextChangedListener(mMyTextWatcher);
		mDelete_group_view.setOnClickListener(this);
		mGroupAddressLayoutView.setOnClickListener(this);
	}

	private void initActionMenu() {
		saveMenuItem = (Button) findViewById(R.id.save_menu_item);
		saveMenuItem.setOnClickListener(this);
		saveMenuItem.setEnabled(false);
		View cancelMenuItem = findViewById(R.id.cancel_menu_item);
		cancelMenuItem.setOnClickListener(this);
	}

	private final LoaderCallbacks<Cursor> loaderMemerCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
			if (c != null) {
				c.moveToPosition(-1);
				while (c.moveToNext()) {
					int id_index = c.getColumnIndex(Contacts._ID);
					if (id_index != -1) {
						long contact_id = c.getLong(id_index);
						if (!mListMembers.contains(contact_id)) {
							mListMembers.add(contact_id);
						}
					}
				}
				int num = c.getCount();
				String addressNumStr = getResources().getString(
						R.string.group_item_count, num);
				mGroupAddressNumView.setText(addressNumStr);
			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			CursorLoader cursorLoader = new CursorLoader(
					WearContactEditGroupActivity.this);
			Uri uri = Contacts.CONTENT_URI;
			cursorLoader.setUri(uri);
			cursorLoader.setProjection(ContactQuery.CONTACT_PROJECTION);
			if (groupUri != null) {
				long groupId = ContentUris.parseId(groupUri);
				if (groupId > 0)
					ConfigLoaderSelectionUtils.configGroupSelection(
							cursorLoader, 0, groupId);
			} else {
				return null;
			}
			return cursorLoader;
		}
	};

	private final LoaderCallbacks<Cursor> loaderGroupCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
//			if (c != null) {
//				c.moveToPosition(-1);
//				while (c.moveToNext()) {
//					int photo_index = c
//							.getColumnIndex(GroupListLoaderUtil.GROUP_PHOTO_DATA);
//					if (photo_index != -1) {
//						byte[] str = c.getBlob(photo_index);
//						if (str != null && image_resid == 0) {
//							final Bitmap bitmap = BitmapFactory
//									.decodeByteArray(str, 0, str.length);
//							mGroupPhotoView.setImageBitmap(bitmap);
//						} else {
//							mGroupPhotoView
//									.setImageResource(R.drawable.ic_friends);
//						}
//					}
//				}
//			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			if (groupUri != null) {
				long groupId = ContentUris.parseId(groupUri);
				return new GroupMetaDataLoader(
						WearContactEditGroupActivity.this, groupId);
			} else {
				if (image_resid == 0) {
					mGroupPhotoView.setImageResource(R.drawable.ic_friends);
				}
				return null;
			}
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
		getLoaderManager().initLoader(0, null, loaderMemerCallbacks);
		getLoaderManager().initLoader(1, null, loaderGroupCallbacks);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(0);
		getLoaderManager().destroyLoader(1);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.save_menu_item:
			if (groupUri != null) {
				updateGroup();
			} else {
				saveGroup();
			}
			break;
		case R.id.cancel_menu_item:
			if (saveMenuItem.isEnabled()) {
				showOnWindosDismissedDialog();
			} else {
				finish();
			}
			break;
		case R.id.edit_group_photo_img:
			Intent intent1 = new Intent();
			intent1.setClass(this, WearContactSelImgActivity.class);
			startActivityForResult(intent1, REQUEST_PHOTO_RESULT);
			break;
		case R.id.edit_address_l:
			// if (groupUri != null) {
			mListMembersToAdd.clear();
			mListMembersToRemove.clear();
			Intent intent = new Intent(this,
					WearSelectGroupContactActivity.class);
			intent.putExtra(WearContactGroupListActivity.GROUP_TITLE, title);
			int i = 0;
			long[] ids = new long[mListMembers.size()];
			for (long id : mListMembers) {
				ids[i++] = id;
			}
			intent.putExtra(EXTRA_PHONE_IDSI, ids);
			intent.setData(groupUri);
			startActivityForResult(intent, REQUEST_RESULT);
			// }
			break;
		case R.id.delete_group_btn:
			showDeleteGroupDialog();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case REQUEST_PHOTO_RESULT:
			if (data != null) {
				Bundle data1 = data.getExtras();
				int index = data1.getInt(WearContactSelImgActivity.IMAGE_INDEX);
				image_resid = WearContactSelImgActivity.imageIds[index];
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						image_resid);
				mGroupPhotoView.setImageBitmap(bmp);
				saveMenuItem.setEnabled(true);
			}
			break;
		case REQUEST_RESULT:
			long[] ids = data
					.getLongArrayExtra(WearContactEditGroupActivity.EXTRA_PHONE_IDSO);
			if (ids != null) {
				String addressNumStr = getResources().getString(
						R.string.group_item_count, ids.length);
				mGroupAddressNumView.setText(addressNumStr);
				ArrayList<Long> tempList = new ArrayList<Long>();
				for (int i = 0; i < ids.length; i++) {
					tempList.add(ids[i]);
				}
				mListMembersToAdd.addAll(tempList);
				mListMembersToAdd.removeAll(mListMembers);
				mListMembersToRemove.addAll(mListMembers);
				mListMembersToRemove.removeAll(tempList);

				if (mListMembersToAdd.size() != 0
						|| mListMembersToRemove.size() != 0) {
					saveMenuItem.setEnabled(true);
				}
			}
			break;
		default:
			break;
		}
	}

	private void showDeleteGroupDialog() {
		AlertDialog.Builder builder = new Builder(this,
				R.style.WatchDialogTheme);
		String title = getIntent().getExtras().getString(
				WearContactGroupListActivity.GROUP_TITLE, null);
		View view = getLayoutInflater().inflate(R.layout.dialog_view, null);
		// TextView title = (TextView) view.findViewById(R.id.dialog_title);
		TextView msg = (TextView) view.findViewById(R.id.dialog_msg);
		Button cancel_btn = (Button) view.findViewById(R.id.dialog_cancel);
		Button ok_btn = (Button) view.findViewById(R.id.dialog_ok);
		msg.setText(getResources().getString(R.string.delete_group_msg, title));
		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		setDialogBottomShow(alertDialog);
		cancel_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				deleteGroup();
				alertDialog.dismiss();
			}
		});
		alertDialog.show();
	}

	private void setDialogBottomShow(final AlertDialog alertDialog) {
		Window window = alertDialog.getWindow();
		WindowManager.LayoutParams wmlp = window.getAttributes();
		wmlp.gravity = Gravity.BOTTOM;
		window.setAttributes(wmlp);
		alertDialog.setCancelable(false);
	}

	private void deleteGroup() {
		Intent saveIntent = null;
		saveIntent = WearContactSaveService.createGroupDeletionIntent(this,
				group_id, this.getClass(),
				WearContactBaseActivity.ACTION_DELETE_GROUP_COMPLETED);
		startService(saveIntent);
		Intent intent = new Intent();
		boolean isEditMainActivityFlag = getIntent().getBooleanExtra(
				WearContactEditMainActivity.EDIT_MAIN_ACTIVITY_FALG, false);
		if (isEditMainActivityFlag) {
			intent.setClass(this, WearContactEditMainActivity.class);
		} else {
			intent.setClass(this, WearContactMainActivity.class);
		}
		startActivity(intent);
		finish();
	}

	private void saveGroup() {
		Intent saveIntent = null;
		// Create array of raw contact IDs for contacts to add to the
		// group
		long[] membersToAddArray = convertToArray(mListMembersToAdd);

		// Create the save intent to create the group and add members at
		// the same time
		if (image_resid != 0) {
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					image_resid);
			byte[] photo = ContactPhotoUtils.compressBitmap(bmp);
			saveIntent = WearContactSaveService.createNewGroupIntent(this,
					mGroupNameView.getText().toString(), membersToAddArray,
					photo, this.getClass(),
					WearContactBaseActivity.ACTION_SAVE_GROUP_COMPLETED);
		} else {
			saveIntent = WearContactSaveService.createNewGroupIntent(this,
					mGroupNameView.getText().toString(), membersToAddArray,
					null, this.getClass(),
					WearContactBaseActivity.ACTION_SAVE_GROUP_COMPLETED);
		}

		startService(saveIntent);
	}

	private void updateGroup() {
		Intent saveIntent = null;
		// Create array of raw contact IDs for contacts to add to the
		// group
		long[] membersToAddArray = convertToArray(mListMembersToAdd);
		// Create array of raw contact IDs for contacts to add to the
		// group
		long[] membersToRemoveArray = convertToArray(mListMembersToRemove);
		// Create the update intent (which includes the updated group
		// name if necessary)
		if (image_resid != 0) {
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					image_resid);
			byte[] photo = ContactPhotoUtils.compressBitmap(bmp);
			saveIntent = WearContactSaveService.createGroupUpdateIntent(this,
					group_id, mGroupNameView.getText().toString(),
					membersToAddArray, membersToRemoveArray, photo,
					this.getClass(),
					WearContactBaseActivity.ACTION_UPDATE_GROUP_COMPLETED);
		} else {
			saveIntent = WearContactSaveService.createGroupUpdateIntent(this,
					group_id, mGroupNameView.getText().toString(),
					membersToAddArray, membersToRemoveArray, null,
					this.getClass(),
					WearContactBaseActivity.ACTION_UPDATE_GROUP_COMPLETED);
		}
		startService(saveIntent);
		finish();
	}

	private long[] convertToArray(List<Long> listMembers) {
		int size = listMembers.size();
		long[] membersArray = new long[size];
		for (int i = 0; i < size; i++) {
			membersArray[i] = listMembers.get(i);
		}
		return membersArray;
	}

	private class MyTextWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			String name = mGroupNameView.getText().toString();
			if (name != null && !TextUtils.isEmpty(name)) {
				saveMenuItem.setEnabled(true);
			} else {
				saveMenuItem.setEnabled(false);
			}
		}

		@Override
		public void afterTextChanged(Editable s) {

		}

	}

	private void showOnWindosDismissedDialog() {
		AlertDialog.Builder builder = new Builder(this,
				R.style.WatchDialogTheme);
		View view = getLayoutInflater().inflate(R.layout.dialog_view, null);
		// TextView title = (TextView) view.findViewById(R.id.dialog_title);
		TextView msg = (TextView) view.findViewById(R.id.dialog_msg);
		Button cancel_btn = (Button) view.findViewById(R.id.dialog_cancel);
		Button ok_btn = (Button) view.findViewById(R.id.dialog_ok);
		msg.setText(R.string.edit_group_swiperight_warning);
		builder.setView(view);
		final AlertDialog alertDialog = builder.create();
		setDialogBottomShow(alertDialog);
		cancel_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
				finish();
			}
		});
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (groupUri != null) {
					updateGroup();
				} else {
					saveGroup();
				}
				alertDialog.dismiss();
				finish();
			}
		});
		alertDialog.show();
	}
}
